﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Aspx_Tree : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Demo.Data.MatrixData data = new Data.MatrixData("datuhe");
                DataTable dt = data.FetchDataTable(PetaPoco.Sql.Builder
                    .Append("select * from 基础_物料分类 order by 排序号"));

                TreeNode rootNode = new TreeNode();
                rootNode.Value = "0";
                rootNode.Text = "根节点";
                tree.Nodes.Add(rootNode);
                buildChildren(rootNode, dt, "物料分类ID", "物料分类名称", "父物料分类ID");

                TreeView tv = new TreeView();
            }
        }


        private void buildChildren(TreeNode parent, DataTable dt, string idField, string textField, string parentIdField)
        {
            var table = dt;
            string filter = string.Format("{0}='{1}'", parentIdField, parent.Value);
            DataRow[] rows = table.Select(filter);
            if (rows != null)
            {
                int count = rows.Count();
                for (int i = 0; i < count; i++)
                {
                    DataRow row = rows[i];
                    TreeNode node = new TreeNode();
                    node.Value = row[idField].ToString();
                    node.Text = row[textField].ToString();
                    node.Expanded = false;

                    buildChildren(node, dt, idField, textField,parentIdField);

                    parent.ChildNodes.Add(node);
                }
            }
        }
    }
}